# -*- coding: utf-8 -*-
'''
| @author: olivia.dou
| Created on: 2020/1/17 15:55
| desc: 和模板映射关系相关的功能
'''

import logging,traceback,requests
import pandas as pd
import base.globalvars as glo
from base.getdata import get_header
from util.db_util import execute_query
from proj_spec.DAS.File import get_file_params_for_template_mapping_crieria,get_file_sector,get_file_entity_code
from proj_spec.DAS.basedata import get_entity_tag_of_entity

#Todo: 使用文件查询，调用使用页面参数report_year,report_period,category_id,type_id,tag_ids查询
#def get_fit_mappings(report_year,report_period,category_id,type_id,tag_ids):
def get_fit_mappings(file_id):
    """获取和文件匹配的映射关系id的列表

    :param file_id: 文件id

    :return: 和指定文件相匹配的映射关系id的列表
    """


    report_year,report_period,category_id,type_id,tag_ids_str = get_file_params_for_template_mapping_crieria(file_id)
    if tag_ids_str is None:
        tag_ids_str = ""

    # 从全局变量中查询，若没有匹配的记录，则根据财年/财季、大类、小类、文件标签查询匹配的映射，并保存到全局变量
    if glo.get_value("template_mapping_dict",defValue={})=={}:#未找到对应的全局变量
        glo.set_value("template_mapping_dict",{})
    elif (report_year,report_period,category_id,type_id,tag_ids_str) in glo.get_value("template_mapping_dict").keys():
        return glo.get_value("template_mapping_dict")[report_year,report_period,category_id,type_id,tag_ids_str]

    entity_code=get_file_entity_code(file_id)
    entity_tag = get_entity_tag_of_entity(entity_code)
    if entity_tag is None or entity_tag=='':
        entity_tag_substr = " (a.entity_tags is null or a.entity_tags ='')" #若实体无实体标签，则匹配的criteria必须不限制实体标签
    else:
        entity_tag_substr = " (a.entity_tags like '%%%s%%' or a.entity_tags is null or a.entity_tags='')"%entity_tag #若实体有实体标签A，匹配的criteria要么不限制实体标签，要么包含实体标签A
    biz_group = get_file_sector(file_id)

    report_quarter = report_period // 3
    #t_das_file_operation_audit表作用：连续id
    # DAS-3881 workflow 模板计算匹配合适的映射关系修改: 原通过 文件标签过滤匹配的映射关系，修改为 通过实体标签过滤
    sql = """select distinct a.mapping_id from t_das_template_criteria a
                    join t_das_template_mapping m
                    on m.id=a.mapping_id
                    where a.file_category_id=%s and a.file_type_id =%s and %s and m.biz_group='%s' and m.status=0 and 
                    (
                    '%sQ%s' between concat(start_fy,start_fq) and concat(end_fy,end_fq) 
                    or 
                    (('%s' between start_fy and end_fy) and '%s'>=start_fq and (end_fq='' or end_fq is null))
                    or
                    ('%sQ%s' >=concat(start_fy,start_fq) and (end_fy='' or end_fy is null) and (end_fq='' or end_fq is null))
                    )
                    """ \
          %(category_id,type_id,entity_tag_substr,biz_group, report_year,report_quarter,report_year,report_quarter,report_year,report_quarter)

    try:
        res = execute_query(sql)

        return [row[0] for row in res] #TODO: 给template_mapping_dict赋值，避免重复查询
    except Exception as e:
        logging.error(e)
        traceback.print_exc()
        return []

def get_template_calc_mappings(file_id, start_time_str):
    """获取文件模板计算时调用到的mapping id

    :param file_id: 文件id
    :param start_time_str: 起始时间的字符串，格式为YYYY-mm-DD HH:MM:SS

    :return: 指定文件由指定时间开始的模板计算调用到的mapping id
    """

    #start_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(start_time_str + 8 * 60 * 60)) #转成gmt+8时间,再转成字符串格式
    sql = "select distinct mapping_id from t_das_dashboard_phase3_detail where file_id=%s and upt>='%s'"%(file_id, start_time_str)

    try:
        res = execute_query(sql)
        return [row[0] for row in res]
    except Exception as e:
        logging.error(e)
        traceback.print_exc()
        return []


def get_mapping_formular_id(mapping_group, mapping_name, source_code, target_code):
    """查询指定映射关系上科目公式id

    :param mapping_group: 映射关系分组
    :param mapping_name: 映射关系名称
    :param source_code: 源节点科目编码
    :param target_code: 目标节点科目编码

    :return: 科目计算公式id
    """
    results = execute_query(
        "SELECT c.id FROM t_das_std_calc_formular c LEFT JOIN t_das_template_mapping m "
        "ON c.mapping_id=m.id WHERE m.mapping_group='%s' and m.mapping_name='%s'AND c.source_code='%s' AND c.target_code='%s'" % (
            mapping_group, mapping_name, source_code, target_code))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("get_mapping_formular_id: %s" % e)
        return None

def get_templatemapping_id(mapping_group, mapping_name):
    """根据映射关系分组和名称查询模板映射id

    :param mapping_group: 映射关系分组
    :param mapping_name: 映射关系名称

    :return: 模板映射id
    """

    results = execute_query(
        "SELECT id FROM t_das_template_mapping  WHERE mapping_group='%s' and mapping_name='%s'order by upt desc" % (
            mapping_group, mapping_name))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None

def get_template_criteria_id( mapping_group, mapping_name):
    """根据映射关系查询映射适用范围最新一条记录id

    :param mapping_group: 映射关系分组
    :param mapping_name: 映射关系名称

    :return: 映射适用范围id
    """

    results = execute_query(
        "SELECT c.id FROM t_das_template_criteria c LEFT JOIN t_das_template_mapping m "
        "ON c.mapping_id=m.id WHERE m.mapping_group='%s' and m.mapping_name='%s' order by c.upt desc" % (
            mapping_group, mapping_name))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None

def get_mapping_info(**kwargs):
    """获取指定映射关系的基本信息

    :param kwargs:
        | id: mapping id
        | mapping_group: 映射分组名称
        | mapping_name: 映射名称

    :return: 映射关系的基本信息
    """

    if 'id' in kwargs:
        condition = "where id = %s"%kwargs['id']
    elif 'mapping_group' in kwargs and 'mapping_name' in kwargs:
        condition = "where mapping_group='%s' and mapping_name='%s'"%(kwargs['mapping_group'],kwargs['mapping_name'])
    else:
        logging.error("get_mapping_info: mapping id or mapping group+mapping name required!")
        return pd.Series([])

    #sql = "select id,mapping_group,mapping_name,biz_group,src_template_id,dest_template_id from t_das_template_mapping %s"%condition
    sql = "select * from t_das_template_mapping %s" % condition
    try:
        #res = execute_query(sql)
        res = execute_query(sql, result_type="dict")
        #result = pd.Series(res[0],index=["id","mapping_group","mapping_name","biz_group","src_template_id","dest_template_id"])
        result = res[0]
        return result
    except Exception as e:
        logging.error(e)
        traceback.print_exc()
        #return pd.Series([])
        return {}


def add_mapping(mapping_id, src_tmpl_fin_item_id, tgt_tmpl_fin_item_id):
    """

    :param mapping_id: 映射id
    :param src_tmpl_fin_item_id: 源模板科目id
    :param tgt_tmpl_fin_item_id: 目标模板科目id

    :return:
    """


    payload = {
                "mappingId": mapping_id,
                "formular": 0,
                "operator": "+",
                "groupName": None,
                "groupPriority": 0,
                "itemType": 0,
                "mulFactor": 1,
                "divFactor": 1,
                "minIncluded": "",
                "groupFunction": "",
                "validCondition": 0,
                "sourceTemplateFinItemId": src_tmpl_fin_item_id,
                "targetTemplateFinItemId": tgt_tmpl_fin_item_id,
                "refTemplateFinItemId": ""
            }

    from base.get_config import get_header_file
    root_url = glo.get_value("url10")
    headers = get_header(get_header_file(), "header2")

    res = requests.post(root_url + "/das/template/mapping/item",headers = headers, json=payload)
    assert res.status_code==200, "添加映射关系失败：mapping_id %s, src_tmpl_fin_item_id %s, tgt_tmpl_fin_item_id %s" %(mapping_id, src_tmpl_fin_item_id, tgt_tmpl_fin_item_id)